import os

from PyUIC.AGI_Connect_Widget import Ui_Connect_Widget
from PyQt5.QtWidgets import QWidget, QFileDialog,QButtonGroup,QInputDialog,QLineEdit,QMessageBox
from utils.load_config import load_cfg,write_cfg

class AGIConnectWidget(QWidget, Ui_Connect_Widget):
    # start_sig = pyqtSignal()
    def __init__(self,thread,cfg,state_init,parent=None):
        super(AGIConnectWidget, self).__init__(parent)
        self.setupUi(self)

        self.th = thread
        self.cfg = cfg
        self.state_init = state_init
        self.tab_idx = self.state_init["UI_State"]
        self.AIOK_checkBox.setChecked(self.state_init['Project_State']["AI_OK_Save"])
        self.init_param()
        # self.th.csv_pth_single.connect(self.read_csv)
        # self.Q_Connect_Button.clicked.connect(self.OpenFolder)
        # self.Q_Start_RadioButton.toggled.connect(self.StartThread)
        #路径设置
        # self.FolderSettinggroupBox.clicked.connect(self.Init_Setting)
        self.Q_AOI_Folder_Button.clicked.connect(self.OpenFolder)
        self.Q_AI_Folder_Button.clicked.connect(self.OpenFolder)
        self.Q_Img_Collection_Button.clicked.connect(self.OpenFolder)
        self.MES_Front_Button.clicked.connect(self.OpenFolder)
        self.MES_Rear_Button.clicked.connect(self.OpenFolder)
        self.FrontMESBackup_Button.clicked.connect(self.OpenFolder)
        self.RearMESBackup_Button.clicked.connect(self.OpenFolder)
        self.Q_AIOK_Collection_Button.clicked.connect(self.OpenFolder)
        self.Q_AOI_Folder_LineEdit.editingFinished.connect(self.ChangeSetting)
        self.Q_AI_Folder_LineEdit.editingFinished.connect(self.ChangeSetting)
        self.MES_Front_LlineEdit.editingFinished.connect(self.ChangeSetting)
        self.MES_Rear_LlineEdit.editingFinished.connect(self.ChangeSetting)
        self.Q_Img_Collection_LineEdit.editingFinished.connect(self.ChangeSetting)
        self.FrontMESBackup_LineEdit.editingFinished.connect(self.ChangeSetting)
        self.RearMESBackup_LineEdit.editingFinished.connect(self.ChangeSetting)
        self.AIOK_checkBox.toggled.connect(self.ChangePathSetting)



        self.groupbuttonBox = QButtonGroup(self.groupbox_reschange)
        self.groupbuttonBox.addButton(self.NG_Res_radioButton,0)
        self.groupbuttonBox.addButton(self.OK_Res_radioButton,1)
        self.groupbuttonBox.addButton(self.Random_Res_radioButton,2)
        self.groupbuttonBox.addButton(self.NoChanges_Res_radioButton,3)
        self.OK_Res_radioButton.hide()
        self.Random_Res_radioButton.hide()
        self.NoChanges_Res_radioButton.hide()
        self.Q_Start_CheckBox.hide()
        # self.MES_Rear_LlineEdit.hide()
        # self.MES_Rear_Button.hide()
        self.Q_MES_CheckBox.hide()
        self.Q_MES2_CheckBox.hide()
        self.Collection_checkBox.hide()

    def init_param(self):
        if self.tab_idx==0:
            self.Q_AOI_Folder_Button.setText('SPI_Path')
            self.Q_Type_ComboBox.setCurrentIndex(0)
            self.AOI_Folder = self.cfg["PemtronSPI"]["SPI_Path"]
            self.Q_AOI_Folder_LineEdit.setText(self.AOI_Folder)
            self.AI_Folder = self.cfg["PemtronSPI"]["AI_Path"]
            self.Q_AI_Folder_LineEdit.setText(self.AI_Folder)
            self.Img_Connection_Folder = self.cfg["PemtronSPI"]["Data_Collection"]
            self.Q_Img_Collection_LineEdit.setText(self.Img_Connection_Folder)
            self.IP_Adress = self.cfg["PemtronSPI"]["DataBaseIP"][1]
            self.MES_Folder = self.cfg["PemtronSPI"]["MES_Front"]
            self.MES_Folder2 = self.cfg["PemtronSPI"]["MES_Rear"]
            self.MES_Front_LlineEdit.setText(self.MES_Folder)
            self.MES_Rear_LlineEdit.setText(self.MES_Folder2)
            self.MES_Collect_Folder = self.cfg["PemtronSPI"]["FrontMESBackup"]
            self.FrontMESBackup_LineEdit.setText(self.MES_Collect_Folder)
            self.FrontMESBackup_LineEdit.setText(self.MES_Collect_Folder)
            self.RearMESBackup_Folder = self.cfg["PemtronSPI"]["RearMESBackup"]
            self.RearMESBackup_LineEdit.setText(self.RearMESBackup_Folder)
            self.AI_Image_Folder = ''
            self.AI_OK_Folder = self.cfg["PemtronSPI"]["AI_OK_Folder"]
            self.Q_AIOK_Collection_LineEdit.setText(self.AI_OK_Folder)
            # self.Q_AOI_Image_lineEdit.hide()
            # self.Q_AOI_Image_pushButton.hide()
            # self.Q_AI_Folder_Button.hide()
            # self.Q_AI_Folder_LineEdit.hide()
        elif self.tab_idx==1:
            self.Q_AOI_Folder_Button.setText('AOI_Path')
            self.Q_Type_ComboBox.setCurrentIndex(1)
            self.AOI_Folder = self.cfg["PemtronAOI"]["AOI_Path"]
            self.Q_AOI_Folder_LineEdit.setText(self.AOI_Folder)
            self.AI_Folder = self.cfg["PemtronAOI"]["AI_Path"]
            self.Q_AI_Folder_LineEdit.setText(self.AI_Folder)
            self.Img_Connection_Folder = self.cfg["PemtronAOI"]["Data_Collection"]
            self.Q_Img_Collection_LineEdit.setText(self.Img_Connection_Folder)
            self.IP_Adress = self.cfg["PemtronAOI"]["DataBaseIP"][1]
            # self.AI_Image_Folder = self.cfg["PemtronAOI"]["AOI图片路径"]
            self.MES_Folder = self.cfg["PemtronAOI"]["MES_Front"]
            self.MES_Folder2 = self.cfg["PemtronAOI"]["MES_Rear"]
            if self.MES_Folder2 == self.MES_Folder:
                self.MES_Folder2 = ''
            self.MES_Front_LlineEdit.setText(self.MES_Folder)
            self.MES_Rear_LlineEdit.setText(self.MES_Folder2)
            self.MES_Collect_Folder = self.cfg["PemtronAOI"]["FrontMESBackup"]
            self.FrontMESBackup_LineEdit.setText(self.MES_Collect_Folder)
            self.RearMESBackup_Folder = self.cfg["PemtronSPI"]["RearMESBackup"]
            self.RearMESBackup_LineEdit.setText(self.RearMESBackup_Folder)
            self.AI_OK_Folder = self.cfg["PemtronAOI"]["AI_OK_Folder"]
            self.Q_AIOK_Collection_LineEdit.setText(self.AI_OK_Folder)
            # self.Q_AOI_Image_lineEdit.setText(self.AI_Image_Folder)
        self.OCR_Root = self.cfg['OCR_ROOT']
        self.POT_Root = self.cfg['POT_ROOT']
            # self.Q_AOI_Image_lineEdit.hide()
            # self.Q_AOI_Image_pushButton.hide()

    # def Init_Setting(self):
    #     if self.FolderSettinggroupBox.isChecked():
    #         password, ok = QInputDialog.getText(self, "Enter Passward", 'Enter Passward',
    #                                                       QLineEdit.Password)
    #         # print(password,ok)
    #         if password == self.state_init["Passward"] and ok:
    #             pass
    #
    #         else:
    #             self.FolderSettinggroupBox.setChecked(False)
    def OpenFolder(self):
        sender = self.sender().text()
        if sender == 'AOI_Path' or sender == 'SPI_Path':
            self.AOI_Folder = QFileDialog.getExistingDirectory(self, "Select Folder", self.AOI_Folder)
            self.Q_AOI_Folder_LineEdit.setText(self.AOI_Folder)
            if self.Q_Type_ComboBox.currentIndex()==0:
                self.cfg["PemtronSPI"]["SPI_Path"] = self.AOI_Folder
            elif self.Q_Type_ComboBox.currentIndex()==1:
                self.cfg["PemtronAOI"]["AOI_Path"] = self.AOI_Folder
            # self.ChangeConfiger("ImgFolder", self.ImgFolder)
        elif sender == 'AI_Path':
            self.AI_Folder = QFileDialog.getExistingDirectory(self, "Select Folder", self.AI_Folder)
            self.Q_AI_Folder_LineEdit.setText(self.AI_Folder)
            if self.Q_Type_ComboBox.currentIndex()==0:
                self.cfg["PemtronSPI"]["AI_Path"] = self.AI_Folder
                self.state_init["UI_State"] = 0
            elif self.Q_Type_ComboBox.currentIndex()==1:
                self.cfg["PemtronAOI"]["AI_Path"] = self.AI_Folder
                self.state_init["UI_State"] = 1
            # self.ChangeConfiger("GoldenImageFolder", self.GoldenImageFolder)
        elif sender == 'Data_Collection':
            self.Img_Connection_Folder = QFileDialog.getExistingDirectory(self, "Select Folder",
                                                                          self.Img_Connection_Folder)
            self.Q_Img_Collection_LineEdit.setText(self.Img_Connection_Folder)
            if self.Q_Type_ComboBox.currentIndex()==0:
                self.cfg["PemtronSPI"]["Data_Collection"] = self.Img_Connection_Folder
                self.state_init["UI_State"] = 0
            elif self.Q_Type_ComboBox.currentIndex()==1:
                self.cfg["PemtronAOI"]["Data_Collection"] = self.Img_Connection_Folder
                self.state_init["UI_State"] = 1
        elif sender == 'MES_Front':
            self.MES_Folder = QFileDialog.getExistingDirectory(self,'Select Folder',self.MES_Folder)
            self.MES_Front_LlineEdit.setText(self.MES_Folder)
            if self.Q_Type_ComboBox.currentIndex()==0:
                self.cfg["PemtronSPI"]["MES_Front"] = self.MES_Folder
                self.state_init["UI_State"] = 0
            elif self.Q_Type_ComboBox.currentIndex()==1:
                self.cfg["PemtronAOI"]["MES_Front"] = self.MES_Folder
                self.state_init["UI_State"] = 1
        elif sender == 'MES_Rear':
            self.MES_Folder2 = QFileDialog.getExistingDirectory(self,'Select Folder',self.MES_Folder2)
            if self.MES_Folder2 == self.MES_Folder:
                self.MES_Folder2 = ''
            self.MES_Rear_LlineEdit.setText(self.MES_Folder2)
            if self.Q_Type_ComboBox.currentIndex()==0:
                self.cfg["PemtronSPI"]["MES_Rear"] = self.MES_Folder2
                self.state_init["UI_State"] = 0
            elif self.Q_Type_ComboBox.currentIndex()==1:
                self.cfg["PemtronAOI"]["MES_Rear"] = self.MES_Folder2
                self.state_init["UI_State"] = 1
        elif sender == 'FrontMESBackup':
            self.MES_Collect_Folder = QFileDialog.getExistingDirectory(self, 'Select Folder', self.MES_Collect_Folder)
            self.FrontMESBackup_LineEdit.setText(self.MES_Collect_Folder)
            if self.Q_Type_ComboBox.currentIndex() == 0:
                self.cfg["PemtronSPI"]["FrontMESBackup"] = self.MES_Collect_Folder
                self.state_init["UI_State"] = 0
            elif self.Q_Type_ComboBox.currentIndex() == 1:
                self.cfg["PemtronAOI"]["FrontMESBackup"] = self.MES_Collect_Folder
                self.state_init["UI_State"] = 1
        elif sender == 'RearMESBackup':
            self.RearMESBackup_Folder = QFileDialog.getExistingDirectory(self, 'Select Folder',
                                                                       self.RearMESBackup_Folder)
            self.RearMESBackup_LineEdit.setText(self.RearMESBackup_Folder)
            if self.Q_Type_ComboBox.currentIndex() == 0:
                self.cfg["PemtronSPI"]["RearMESBackup"] = self.RearMESBackup_Folder
                self.state_init["UI_State"] = 0
            elif self.Q_Type_ComboBox.currentIndex() == 1:
                self.cfg["PemtronAOI"]["RearMESBackup"] = self.RearMESBackup_Folder
                self.state_init["UI_State"] = 1
            pass

        elif sender == 'AIOK_Collection':
            self.AI_OK_Folder = QFileDialog.getExistingDirectory(self, "Select Folder", self.AI_OK_Folder)
            self.Q_AIOK_Collection_LineEdit.setText(self.AI_OK_Folder)
            if self.Q_Type_ComboBox.currentIndex()==0:
                self.cfg["PemtronSPI"]["AI_OK_Folder"] = self.AI_OK_Folder
                self.state_init["UI_State"] = 0
            elif self.Q_Type_ComboBox.currentIndex()==1:
                self.cfg["PemtronAOI"]["AI_OK_Folder"] = self.AI_OK_Folder
                self.state_init["UI_State"] = 1
        write_cfg('./config/path_settings.yaml',self.cfg)
        write_cfg('./config/settings.yaml', self.state_init)

    def ChangePathSetting(self):
        ischecked = self.AIOK_checkBox.isChecked()
        self.state_init['Project_State']['AI_OK_Save'] = ischecked
        write_cfg('./config/settings.yaml', self.state_init)
    def ChangeSetting(self):
        sender = self.sender()
        folder = sender.text()
        if not os.path.exists(folder) and folder != '':
            # sender.setText()
            sender.undo()
            QMessageBox.warning(self,'Warning','Folder Not Exist!!!',QMessageBox.Yes,QMessageBox.Yes)

            return
        Combo_current_idx = self.Q_Type_ComboBox.currentIndex()
        if Combo_current_idx == 0:
            if self.Q_AOI_Folder_LineEdit.isModified():
                self.AOI_Folder = self.Q_AOI_Folder_LineEdit.text()
                self.cfg["PemtronSPI"]["SPI_Path"] = self.AOI_Folder
            if self.Q_AI_Folder_LineEdit.isModified():
                self.AI_Folder = self.Q_AI_Folder_LineEdit.text()
                self.cfg["PemtronSPI"]["AI_Path"] = self.AI_Folder
            if self.MES_Front_LlineEdit.isModified():
                self.MES_Folder = self.MES_Front_LlineEdit.text()
                self.cfg["PemtronSPI"]["MES_Front"] = self.MES_Folder
            if self.MES_Rear_LlineEdit.isModified():
                self.MES_Folder2 = self.MES_Rear_LlineEdit.text()
                if self.MES_Folder2 == self.MES_Folder:
                    self.MES_Folder2 = ''
                self.cfg["PemtronSPI"]["MES_Rear"] = self.MES_Folder2
            if self.FrontMESBackup_LineEdit.isModified():
                self.MES_Collect_Folder = self.FrontMESBackup_LineEdit.text()
                self.cfg["PemtronSPI"]["FrontMESBackup"] = self.MES_Collect_Folder
            if self.RearMESBackup_LineEdit.isModified():
                self.RearMESBackup_Folder = self.RearMESBackup_LineEdit.text()
                self.cfg["PemtronSPI"]["RearMESBackup"] = self.RearMESBackup_Folder
            if self.Q_Img_Collection_LineEdit.isModified():
                self.Img_Connection_Folder = self.Q_Img_Collection_LineEdit.text()
                self.cfg["PemtronSPI"]["Data_Collection"] = self.Img_Connection_Folder
            if self.Q_AIOK_Collection_LineEdit.isModified():
                self.AI_OK_Folder = self.Q_AIOK_Collection_LineEdit.text()
                self.cfg["PemtronSPI"]["AI_OK_Folder"] = self.AI_OK_Folder


        elif self.tab_idx==1:
            if self.Q_AOI_Folder_LineEdit.isModified():
                self.AOI_Folder = self.Q_AOI_Folder_LineEdit.text()
                self.cfg["PemtronAOI"]["AOI_Path"] = self.AOI_Folder
            if self.Q_AI_Folder_LineEdit.isModified():
                self.AI_Folder = self.Q_AI_Folder_LineEdit.text()
                self.cfg["PemtronAOI"]["AI_Path"] = self.AI_Folder
            if self.MES_Front_LlineEdit.isModified():
                self.MES_Folder = self.MES_Front_LlineEdit.text()
                self.cfg["PemtronAOI"]["MES_Front"] = self.MES_Folder
            if self.MES_Rear_LlineEdit.isModified():
                self.MES_Folder2 = self.MES_Rear_LlineEdit.text()
                if self.MES_Folder2 == self.MES_Folder:
                    self.MES_Folder2 = ''
                self.cfg["PemtronAOI"]["MES_Rear"] = self.MES_Folder2
            if self.FrontMESBackup_LineEdit.isModified():
                self.MES_Collect_Folder = self.FrontMESBackup_LineEdit.text()
                self.cfg["PemtronAOI"]["FrontMESBackup"] = self.MES_Collect_Folder
            if self.RearMESBackup_LineEdit.isModified():
                self.RearMESBackup_Folder = self.RearMESBackup_LineEdit.text()
                self.cfg["PemtronSPI"]["RearMESBackup"] = self.RearMESBackup_Folder
            if self.Q_Img_Collection_LineEdit.isModified():
                self.Img_Connection_Folder = self.Q_Img_Collection_LineEdit.text()
                self.cfg["PemtronAOI"]["Data_Collection"] = self.Img_Connection_Folder
            if self.Q_AIOK_Collection_LineEdit.isModified():
                self.AI_OK_Folder = self.Q_AIOK_Collection_LineEdit.text()
                self.cfg["PemtronAOI"]["AI_OK_Folder"] = self.AI_OK_Folder
        write_cfg('./config/path_settings.yaml', self.cfg)
        # write_cfg('./config/settings.yaml', self.state_init)
    # def StartThread(self):
    #     if self.Q_Start_RadioButton.isChecked():
    #         self.start_sig()
    #         self.th.add_watchlist(self.AOI_Folder, self.AI_Folder)
    #         self.th.Start()
    #     else:
    #         self.th.Stop()
    #     pass

    # def read_csv(self,csv_path):
    #     data = []
    #     self.arr_list = []
    #     with open(csv_path) as csvfile:
    #         csv_reader = csv.reader(csvfile)  # 使用csv.reader读取csvfile中的文件
    #         # header = next(csv_reader)        # 读取第一行每一列的标题
    #         for row in csv_reader:  # 将csv 文件中的数据保存到data中
    #             arr_id, pad_no,img_res = row[1], row[3],row[6]
    #             self.arr_list.append([arr_id, pad_no,img_res])
        #         arr_key = '{}_{}'.format(arr_id, pad_no)
        #         if arr_key in self.test_result:
        #             row[6] = self.test_result[arr_key]
        #         data.append(row)  # 选择某一列加入到data数组中
        #
        # timefolder, base_name = os.path.split(csv_path)
        # dst_csv_folder = timefolder.replace(self.AOI_Folder, self.AI_Folder)
        # if not os.path.exists(dst_csv_folder):
        #     os.makedirs(dst_csv_folder)
        # dst_csv_path = os.path.join(dst_csv_folder, base_name)
        # f = open(dst_csv_path, 'w', newline="", encoding='utf-8')
        # csv_writer = csv.writer(f)
        # for row in data:
        #     csv_writer.writerow(row)
        # f.close()

    # def get_arr_list(self):
    #     try:
    #         return self.arr_list
    #     except Exception as e:
    #         print(e)
    #         return None
